<!-- 用户地址管理 -->
<template>
  <page-header-wrapper>
    <a-card class="table-card">
      <GzSearchForm :searchFunc="searchFunc" :resetFunc="() => { searchData = {}; }" searchConditionNum="6">
        <a-form-item class="table-search-item" label="员工编号">  
          <a-input v-model:value="searchData['employeeNo']" label="员工编号" :placeholder="'员工编号'" />
        </a-form-item>
        <a-form-item class="table-search-item" label="员工姓名"> 
          <a-input v-model:value="searchData['employeeName']" :placeholder="'员工姓名'" />
        </a-form-item>
        <a-form-item class="table-search-item" label="机构号">
          <a-input v-model:value="searchData['agentNo']" :placeholder="'机构号'" />
        </a-form-item>
      </GzSearchForm>
      <GzTable
        ref="infoTableRef"
        :init-data="true"
        :req-table-data-func="reqTableDataFunc"
        :table-columns="tableColumns"
        :search-data="searchData"
        :scrollX="800"
      >
        <template #topBtnSlot>
          <GzUploadExe v-if="$access('ENT_PROXY_EMPLOYEE_INFO_IMPT')" :showUploadList="false" :isNeedImport="true" @updateValue="handleImportData">
            <template #uploadBtn>
              <a-button type="primary">
                <plus-outlined />导入员工
              </a-button>
            </template>
          </GzUploadExe>
          <a-button v-if="$access('ENT_PROXY_EMPLOYEE_INFO_DOWN_TEMPLATE')" type="link" href="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/template/agent_permission_bind_template.xlsx">下载导入员工模板</a-button>
          <a-button v-if="$access('ENT_PROXY_EMPLOYEE_INFO_EXPT')" type="primary" :loading="loadingExport" @click="exportFunc">导出机构员工</a-button>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'businessPermission'">
            <a-switch
              v-if="$access('ENT_PROXY_EMPLOYEE_INFO_APP')"
              :checked="record.businessPermission == 1 ? true : false"
              @change="changeStatus1(record)"
            />
            <template v-else>
              <div v-if="record.businessPermission == 0">
                <a-badge status="error" text="停用" />
              </div>
              <div v-else-if="record.businessPermission == 1">
                <a-badge status="processing" text="启用" />
              </div>
            </template>
          </template>
          <template v-if="column.key === 'operation'">
            <GzTableColumns>
              <!-- <a-button v-if="$access('ENT_FANS_LIST_INFO_SCORE')" type="link" @click="updateAccount(record,record.fansId)">修改账户归属</a-button>
              <a-button v-if="$access('ENT_FANS_LIST_INFO_VIEW')" type="link" @click="resetPsd(record)">重置登录密码</a-button>
              <a-button v-if="$access('ENT_FANS_LIST_INFO_VIEW')" type="link" @click="delData(record)">删除</a-button> -->
            </GzTableColumns>
          </template>
        </template>
      </GzTable>
    </a-card>
    <!-- 是否有展业权限 -->
    <a-modal
      :visible="vdata.stateVisible"
      okText="确定"
      cancelText="取消"
      style="padding: 32px 32px 24px"
      @cancel="() => {
        vdata.stateVisible = false;
      }
      "
      @ok="handleOkFunc"
    >
      <template #title>
        <exclamation-circle-outlined style="color: #faad14; font-size: 22px; margin-right: 20px" />{{ vdata.title }}
      </template>
      <a-form
        ref="formRef"
        :rules="vdata.rules"
        :model="vdata.saveObject"
        layout="horizontal"
        :wrapperCol="{ span: 24 }"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item label="选择小程序" name="appId">
              <a-select v-model:value="vdata.saveObject['appId']" :placeholder="'请选择小程序'">
                <a-select-option v-for="(item,index) in vdata.programsList" :key="index" :value="item.appId">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="选择用户" name="payOpenId">
              <a-select v-model:value="vdata.saveObject['payOpenId']" :placeholder="'请选择用户'" :options="vdata.fansListOptions" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>
  </page-header-wrapper>
</template>

<script lang="ts" setup>
// import { req, API_URL_PROXY_EMPLOYEE_LIST, API_URL_PROXY_EMPLOYEE_IMPORT } from "@/api/manage";
import {$apiAgentEmployeeList,$apiAgentEmployeeAddBatch,$apiAgentEmployeeExport,$apiAgentEmployeeBindBusinessPermission,$getFansInfoForEmployee} from '@/api/proxy/ProxyEmployee/index'
import {$apiAgentApp} from '@/api/proxy/programManage/lite/index'
import { ref, reactive, getCurrentInstance } from 'vue'

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
const loadingExport = ref(false)
const infoTableRef = ref()
const vdata = reactive({
  checked:'',
  stateVisible:false,
  title:'',
  businessPermission:'',
  programsList:[] as any[],
  saveObject:{
    employeeId: '',
    appId: null,
    isBind: '',
    payOpenId: null,
  },
  fansListOptions: [], // 用户列表
  rules:{
    appId:[{required: true, message: '请选择小程序',trigger:'change'}],
    payOpenId:[{required: true, message: '请选择用户',trigger:'change'}],
  }
})

const formRef = ref()

// 搜索条件
const searchData: any = ref({})

let tableColumns = reactive([
  { key: 'agentEmployeeId', title: '机构员工ID', dataIndex: 'agentEmployeeId', fixed: 'left', width: 140, minWidth: 140, maxWidth: 250, tips: '机构员工ID' },
  { key: 'employeeNo', title: '员工编号', dataIndex: 'employeeNo', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'employeeName', title: '员工姓名', dataIndex: 'employeeName', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'employeePhone', title: '员工手机号', dataIndex: 'employeePhone', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'agentNo1', title: '一级机构号', dataIndex: 'agentNo1', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'agentNo2', title: '二级机构号', dataIndex: 'agentNo2', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'agentNo3', title: '三级机构号', dataIndex: 'agentNo3', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'agentNo4', title: '四级机构号', dataIndex: 'agentNo4', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'hierarchyPath', title: '机构层级', dataIndex: 'hierarchyPath', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'businessPermission', title: '小程序展业权限是否开启', dataIndex: 'businessPermission', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'createdAt', title: '创建时间', dataIndex: 'createdAt', width: 140, minWidth: 140, maxWidth: 250, },
  { key: 'remark', title: '备注', dataIndex: 'remark', width: 140, minWidth: 140, maxWidth: 250, },
  // { key: 'operation', title: '操作', dataIndex: 'operation', fixed: 'right', align: 'center', width: 260, },
])
/**
 * 搜索
 */
function searchFunc() {
  infoTableRef.value.refTable(true)
}
// 请求table接口数据
function reqTableDataFunc(params: any) {
  return $apiAgentEmployeeList({ ...params })
}

// 导出
const exportFunc = () =>{
  loadingExport.value = true
  $apiAgentEmployeeExport(searchData.value).then(res=>{
    if(res.successUrl){
      loadingExport.value = false
      $infoBox.message.success('导出成功')
      const successUrl = res.successUrl
      const link = document.createElement('a')
      link.href = successUrl
      link.download = 'filename.xlsx' // 设置下载文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }else{
      loadingExport.value = false
      $infoBox.message.warn('此次没有结果')
    }
  })
}


  function changeStatus1(record) {
    record.businessPermission == '0'?vdata.title = '确认开启?':vdata.title = '确认关闭'
    vdata.saveObject.employeeId=record.agentEmployeeId
    // 把选择框的值清空
    vdata.saveObject.appId = null
    vdata.saveObject.payOpenId = null
    vdata.stateVisible = true
     vdata.businessPermission = record.businessPermission
     vdata.saveObject.isBind = record.businessPermission
    record.businessPermission == '0' ? vdata.businessPermission = '0':vdata.businessPermission = '1'
     $apiAgentApp({type:1,agentNo:''}).then(res=>{
      vdata.programsList = res.records
    })
    $getFansInfoForEmployee({ agentEmployeeId: record.agentEmployeeId }).then(res => {
      vdata.fansListOptions = res.map(item => ({
        label: `${item.phone}-${item.nickName || '未知昵称'}`,
        value: item.payOpenId,
      }))
    })
    // vdata.activityChannelId = record.activityChannelId
  
  }


  function handleOkFunc() {
    formRef.value.validate().then(()=>{
      $apiAgentEmployeeBindBusinessPermission(vdata.saveObject).then(res=>{
          $infoBox.message.success('操作成功')
          vdata.stateVisible = false
         infoTableRef.value.refTable(false)
      })
    })
  }

/**
 * 导入员工
 */
async function handleImportData(value){
  $apiAgentEmployeeAddBatch({ossFileUrl:value}).then(res=>{
    if(res=='success'){
      $infoBox.message.success('导入成功')
    }else{
      const url = res
      const link = document.createElement('a')
      link.href = url
      link.download = 'filename.xlsx' // 设置下载文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      searchFunc()
    }
  })
}
/**
 * 错误处理函数
 */

</script>